// restful api 自动路由生成
// api doc: https://github.com/tunnckoCore/koa-rest-router
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const KoaRouter = require('./router')
const logger = require('../../utils/logger')
const ErrorModel = require('../../model/ErrorModel')
const api = KoaRouter({
  prefix: '/api'
})


const wrap = (path) => {
  let Factory = require(path);
  let Model = new Factory();
  let map = {};
  ['index', 'create', 'update', 'show', 'edit', 'action']
  .forEach((methods) => {
    const fn = Model[methods];
    map[methods] = async (ctx, next) => {
      if (Model[methods]) {
        try {
          return await fn.call(Model, ctx, next)
        } catch (e) {
          // e为ErrorModel实例
          throw(e)
        }
      } else {
        throw(ErrorModel(500, '无效调用', ctx.query.traceId))
      }
    }
  })
  return map
}


module.exports = (controllerPath) => {
  const dirArray = glob.sync(path.join(controllerPath, './*.js'));
  dirArray.forEach((dir) => {
    let dirName = path.basename(dir, '.js');
    api.resource(dirName, wrap(dir), {
      methods: {
        delete: 'POST',
        put: 'POST'
      },
      map: {
        remove: 'action',
        new: 'action'
      }
    })
  })
  console.log(api)
  return api.middleware()
}
